package com.millstein.strategy;

import com.millstein.exception.BizException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description:
 * @author: tsing
 * @create: 2021-09-29 15:47
 */
@Component
public class PayStrategyContext {

    @Autowired
    private List<PayStrategy> strategies;

    private static final Map<String, PayStrategy> strategyContext = new ConcurrentHashMap<>();

    @PostConstruct
    public void initStrategyMap() {
        if (CollectionUtils.isEmpty(strategies)) {
            throw new BizException(50000, "没有支付策略，请配置");
        }
        for (PayStrategy payStrategy : strategies) {
            strategyContext.put(payStrategy.type().name(), payStrategy);
        }
    }

    /**
     * 对外暴露的方法
     * @return
     */
    public PayStrategy getPayStrategy(String payType) {
        return strategyContext.get(payType);
    }
}
